package com.VerificationCode.demo;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.VerificationCode.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
@RequestMapping("/captcha")
@RestController
public class VerificationController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private long VALID_TIME = 60*1000;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {

        ICaptcha captcha = CaptchaUtil.createLineCaptcha(
                captchaProperties.getWidth(), captchaProperties.getHeight());

        captcha.write(response.getOutputStream());
        //禁止缓存
        response.setHeader("Prama","No-cache");
        //设置返回格式
        response.setContentType(("/image.jpeg"));
        //打印验证码
        System.out.println(captcha.getCode());
        //存储session
        session.setAttribute(captchaProperties.getSession().getCode(),captcha.getCode());
        session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
        response.getOutputStream().close();
        //Servlet的OutputStream记得自行关闭哦！
    }
    @RequestMapping("/check")
    public Boolean check(String captchaCode,HttpSession session){
        //参数校验
        //判断用户输入是否和session一致
        //判断是否在有效期内
        if(!StringUtils.hasLength(captchaCode)){
            return false;
        }
        String sessionCode = (String)session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long)session.getAttribute(captchaProperties.getSession().getDate());
        if(captchaCode.equals(sessionCode) && sessionDate != null && System.currentTimeMillis()-sessionDate
                <  VALID_TIME ){

            return true;
        }
        return false;


    }

}
